package com.nulldev.util.crypto.hash;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class SHAHash {
	public static String hashFile(File file) {
        if (file.isDirectory()) {
            List<String> hashes = new ArrayList<String>();
            for (File f : file.listFiles()) {
                hashFile(file);
            }
            try {
                return new String(hash(hashes));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            try {
                return new String(hash(file));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    private static byte[] hash(File file) throws Exception {
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        InputStream input = new FileInputStream(file);
        byte[] buffer = new byte[8192];
        int len = input.read(buffer);
        
        while (len != -1) {
            sha1.update(buffer, 0, len);
            len = input.read(buffer);
        }
        final byte[] d = sha1.digest();
        input.close();
        return d;
    }
    
    private static byte[] hash(Collection<String> hashes) throws Exception {
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        for (String hash : hashes) {
            sha1.update(hash.getBytes());
        }
        return sha1.digest();
    }
}
